package middleware

import (
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"wh-1-backend/internal/consts"
	"wh-1-backend/internal/service"
	"wh-1-backend/internal/utils/lerr"
)

type sMiddleware struct{}

func init() {
	service.RegisterMiddleware(New())
}

func New() *sMiddleware {
	return &sMiddleware{}
}

type DefaultHandlerResponse struct {
	Code    int         `json:"code"`
	Message string      `json:"msg"`
	Data    interface{} `json:"data"`
}

func (m *sMiddleware) MiddlewareHandlerResponse(r *ghttp.Request) {
	g.Dump(r.Request.URL)
	g.Dump(r.Router.Method, r.Router.Uri)
	r.Middleware.Next()
	if r.Response.BufferLength() > 0 {
		return
	}
	var (
		res  interface{}
		msg  string
		err  = r.GetError()
		code = gerror.Code(err)
	)
	if err != nil {
		if code == gcode.CodeNil {
			code = gcode.CodeInternalError
		} else if code == gcode.CodeValidationFailed {
			code = gcode.New(lerr.CodeFail, "", nil)
		}
		msg = err.Error()
	} else {
		code = gcode.New(20000, "操作成功", nil)
		msg = "success"
		res = r.GetHandlerResponse()
	}
	r.Response.WriteJson(DefaultHandlerResponse{
		Code:    code.Code(),
		Message: msg,
		Data:    res,
	})
}

func (m *sMiddleware) Auth(r *ghttp.Request) {
	key := r.Request.Header.Get(consts.AuthHeaderKey)
	if len(key) != 32 {
		r.Response.WriteJsonExit(DefaultHandlerResponse{
			Code:    lerr.CodeAuthFail,
			Message: "用户失效，请重新登录",
		})
	}
	res, err := service.Auth().CheckHeardKey(r.GetCtx(), key)
	if err != nil || res == nil || res.Id == 0 {
		r.Response.WriteJsonExit(DefaultHandlerResponse{
			Code:    lerr.CodeAuthFail,
			Message: "用户失效，请重新登录",
		})
	}
	r.SetCtxVar("user", res)
	r.SetCtxVar(consts.AuthHeaderKey, key)
	r.Middleware.Next()
}
